from django.core import signing
from django.db import transaction
from rest_framework.decorators import api_view
from questionnaire.models import Questionnaire, Question, Options, GradeQuestionAttribute, Submit
from rest_framework.response import Response
from rest_framework import status
from user.models import User

import datetime


# {'questionnaire_id': 'int', 'username': ''}
@api_view(['POST', ])
def checkBeforeEdit(request):
    code = request.data.get('questionnaire_id')
    if code is None:
        return Response({'code': -1, 'msg': '缺少参数'}, status=status.HTTP_400_BAD_REQUEST)
    try:
        value = signing.loads(code)
    except:
        return Response({'msg': '解码失败', 'code': -2}, status=status.HTTP_200_OK)
    questionnaire_id = value['questionnaire_id']
    username = request.data.get('username')
    if Questionnaire.objects.filter(id=questionnaire_id).count() == 0:
        return Response({'code': -1, 'msg': '不存在的问卷'}, status=status.HTTP_400_BAD_REQUEST)
    # if User.objects.filter(username=username).count() == 0:
    #     return Response({'code': -1, 'msg': '不存在的用户'}, status=status.HTTP_400_BAD_REQUEST)
    questionnaire = Questionnaire.objects.get(id=questionnaire_id)
    if questionnaire.username != username:
        return Response({'code': -2, 'msg': '此用户没有修改权限'}, status=status.HTTP_200_OK)
    # return Response({'code': 0, 'msg': 'ok'}, status=status.HTTP_200_OK)
    # if questionnaire.status == 1:
    #     return Response({'code': -3, 'msg': '问卷发布中不可修改'}, status=status.HTTP_200_OK)
    # if Submit.objects.filter(wjId=questionnaire_id).count() != 0:
    #     questionnaire_copy = Questionnaire.objects.create(title=questionnaire.title + '的副本',
    #                                                       username=questionnaire.username,
    #                                                       status=0,  # 副本是未发布状态
    #                                                       desc=questionnaire.desc,
    #                                                       publish_time=questionnaire.publish_time,
    #                                                       start_time=questionnaire.start_time,
    #                                                       end_time=questionnaire.end_time,
    #                                                       is_remind=questionnaire.is_remind,
    #                                                       is_allowed_to_change=questionnaire.is_allowed_to_change,
    #                                                       is_out_of_order=questionnaire.is_out_of_order,
    #                                                       is_set_date=questionnaire.is_set_date,
    #                                                       is_deleted=questionnaire.is_deleted,
    #                                                       show_number=questionnaire.show_number,
    #                                                       type=questionnaire.type,
    #                                                       limit=questionnaire.limit)
    #     questions = Question.objects.filter(wjId=questionnaire_id)
    #     if Question.objects.filter(wjId=questionnaire_id).count() == 0:
    #         return Response({'msg': '该问卷有提交数据 请在副本中编辑', 'code': -4}, status=status.HTTP_200_OK)
    #     # 循环复制问题信息
    #     for q in questions:
    #         question_object = Question.objects.create(
    #             title=q.title,
    #             type=q.type,
    #             wjId=questionnaire_copy.id,
    #             row=q.row,
    #             must=q.must,
    #             remark=q.remark,
    #             score=q.score,
    #             correct_option=q.correct_option,
    #             correct_answer=q.correct_answer
    #         )
    #         options = Options.objects.filter(questionId=q.id)
    #         for option in options:
    #             Options.objects.create(questionId=question_object.id, title=option.title, limit=option.limit,
    #                                    remain=option.limit, is_correct=option.is_correct)
    #         if q.type == 'grade':
    #             g = GradeQuestionAttribute.objects.get(questionId=q.id)
    #             GradeQuestionAttribute.objects.create(questionId=question_object.id,
    #                                                   grade_type=g.grade_type,
    #                                                   degree_max=g.degree_max,
    #                                                   degree_min=g.degree_min,
    #                                                   range=g.range,
    #                                                   start=g.start)
    #     return Response({'code': -4, 'msg': '该问卷有提交数据 请在副本中编辑'}, status=status.HTTP_200_OK)
    else:
        return Response({'code': 0, 'msg': 'ok'}, status=status.HTTP_200_OK)


@api_view(['POST', ])
def ifAllowed(request):
    questionnaire_id = request.data.get('questionnaire_id')
    if questionnaire_id is None:
        return Response({'code': -1, 'msg': '缺少参数'}, status=status.HTTP_400_BAD_REQUEST)
    if Questionnaire.objects.filter(id=questionnaire_id).count() == 0:
        return Response({'code': -1, 'msg': '不存在的问卷'}, status=status.HTTP_400_BAD_REQUEST)
    questionnaire = Questionnaire.objects.get(id=questionnaire_id)
    if questionnaire.status == 1:
        return Response({'code': -3, 'msg': '问卷发布中不可修改'}, status=status.HTTP_200_OK)
    if Submit.objects.filter(wjId=questionnaire_id).count() != 0:
        questionnaire_copy = Questionnaire.objects.create(title=questionnaire.title + '的副本',
                                                          username=questionnaire.username,
                                                          status=0,  # 副本是未发布状态
                                                          desc=questionnaire.desc,
                                                          publish_time=None,
                                                          start_time=None,
                                                          end_time=None,
                                                          is_remind=questionnaire.is_remind,
                                                          is_allowed_to_change=False,
                                                          is_out_of_order=False,
                                                          is_set_date=False,
                                                          is_deleted=questionnaire.is_deleted,
                                                          show_number=False,
                                                          type=questionnaire.type,
                                                          limit=questionnaire.limit)
        questions = Question.objects.filter(wjId=questionnaire_id)
        if Question.objects.filter(wjId=questionnaire_id).count() == 0:
            return Response({'msg': '该问卷有提交数据 请在副本中编辑', 'code': -4}, status=status.HTTP_200_OK)
        # 循环复制问题信息
        for q in questions:
            question_object = Question.objects.create(
                title=q.title,
                type=q.type,
                wjId=questionnaire_copy.id,
                row=q.row,
                must=q.must,
                remark=q.remark,
                score=q.score,
                correct_option=q.correct_option,
                correct_answer=q.correct_answer
            )
            options = Options.objects.filter(questionId=q.id)
            for option in options:
                Options.objects.create(questionId=question_object.id, title=option.title, limit=option.limit,
                                       remain=option.limit, is_correct=option.is_correct)
            if q.type == 'grade':
                g = GradeQuestionAttribute.objects.get(questionId=q.id)
                GradeQuestionAttribute.objects.create(questionId=question_object.id,
                                                      grade_type=g.grade_type,
                                                      degree_max=g.degree_max,
                                                      degree_min=g.degree_min,
                                                      range=g.range,
                                                      start=g.start)
        return Response({'code': -4, 'msg': '该问卷有提交数据 请在副本中编辑'}, status=status.HTTP_200_OK)
    else:
        return Response({'code': 0, 'msg': 'ok'}, status=status.HTTP_200_OK)


@api_view(['POST', ])
def changeStatus(request):
    questionnaire_id = request.data.get('questionnaire_id')
    if questionnaire_id is None:
        return Response({'code': -1, 'msg': '缺少参数questionnaire_id'}, status=status.HTTP_400_BAD_REQUEST)
    if Questionnaire.objects.filter(id=questionnaire_id).count() == 0:
        return Response({'code': -1, 'msg': '不存在的questionnaire_id'}, status=status.HTTP_400_BAD_REQUEST)
    questionnaire = Questionnaire.objects.get(id=questionnaire_id)
    if questionnaire.status == 0:
        questionnaire.status = 1
        questionnaire.save()
        return Response({'code': 0, 'msg': '切换到未发布'}, status=status.HTTP_200_OK)
    else:
        questionnaire.status = 0
        questionnaire.save()
        return Response({'code': 0, 'msg': '切换到已发布'}, status=status.HTTP_200_OK)


@api_view(['POST', ])
def getStatus(request):
    questionnaire_id = request.data.get('questionnaire_id')
    if questionnaire_id is None:
        return Response({'code': -1, 'msg': '缺少参数questionnaire_id'}, status=status.HTTP_400_BAD_REQUEST)
    if Questionnaire.objects.filter(id=questionnaire_id).count() == 0:
        return Response({'code': -1, 'msg': '不存在的questionnaire_id'}, status=status.HTTP_400_BAD_REQUEST)
    questionnaire = Questionnaire.objects.get(id=questionnaire_id)
    return Response({'code': 0, 'msg': '获取成功', 'status': questionnaire.status}, status=status.HTTP_200_OK)


@api_view(['POST', ])
def createQuestionnaire(request):  # 创建一个新的问卷
    username = request.data.get('username')
    type = request.data.get('type')
    if username is None or type is None:
        return Response({'code': -1, 'msg': '缺少参数'}, status=status.HTTP_400_BAD_REQUEST)
    questionnaire = Questionnaire.objects.create(username=username, title='问卷标题',
                                                 desc='为了给您提供更好的服务，希望您能抽出几分钟时间，将您的感受和建议告诉我们，我们非常重视每位用户的宝贵意见，期待您的参与！现在我们就马上开始吧！',
                                                 status=0, type=type)
    value = signing.dumps({'questionnaire_id': questionnaire.id})
    return Response({'code': 0, 'msg': '创建成功', 'questionnaire_id': value}, status=status.HTTP_200_OK)


@api_view(['POST', ])
def code(request):
    questionnaire_id = request.data.get('questionnaire_id')
    if Questionnaire.objects.filter(id=questionnaire_id).count() == 0:
        return Response({'code': -1, 'msg': '不存在的问卷'}, status=status.HTTP_400_BAD_REQUEST)
    value = signing.dumps({'questionnaire_id': questionnaire_id})
    return Response({'code': 0, 'questionnaire_id': value}, status=status.HTTP_200_OK)


@api_view(['POST', ])
def decode(request):
    code = request.data.get('questionnaire_id')
    try:
        value = signing.loads(code)
    except:
        return Response({'msg': '解码失败', 'code': -1}, status=status.HTTP_200_OK)
    return Response({'id': value['questionnaire_id'], 'code': 0}, status=status.HTTP_200_OK)


@api_view(['POST', ])
def getQuestionnaireType(request):
    questionnaire_code = request.data.get('questionnaire_id')
    try:
        value = signing.loads(questionnaire_code)
    except:
        return Response({'msg': '解码失败', 'code': -1}, status=status.HTTP_400_BAD_REQUEST)
    else:
        questionnaire_id = value['questionnaire_id']
        if Questionnaire.objects.filter(id=questionnaire_id).count() == 0:
            return
        questionnaire = Questionnaire.objects.get(id=questionnaire_id)
        if questionnaire.type == 'default':
            return Response({'msg': '普通问卷', 'code': -1}, status=status.HTTP_200_OK)
        if questionnaire.type == 'exam':
            return Response({'msg': '考试问卷', 'code': -1}, status=status.HTTP_200_OK)
        if questionnaire.type == 'vote':
            return Response({'msg': '投票问卷', 'code': -1}, status=status.HTTP_200_OK)
        if questionnaire.type == 'apply':
            return Response({'msg': '报名问卷', 'code': -1}, status=status.HTTP_200_OK)
        if questionnaire.type == 'cardin':
            return Response({'msg': '疫情打卡问卷', 'code': -1}, status=status.HTTP_200_OK)
        else:
            return Response({'msg': '不存在的type', 'code': -1}, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST', ])
def addQuestionnaire(request):  # 修改问卷
    username = request.data.get('username')
    title = request.data.get('title')
    desc = request.data.get('desc')
    questionnaire_id = request.data.get('questionnaire_id')
    if username and title:
        try:
            if questionnaire_id:  # id不为空 更新问卷
                questionnaire = Questionnaire.objects.get(username=username, id=questionnaire_id)
                questionnaire.title = title
                questionnaire.desc = desc
                questionnaire.save()
            else:  # 否则 添加问卷
                questionnaire = Questionnaire.objects.create(username=username, title=title, desc=desc, status=0)
        except Exception as e:
            response = {
                'code': -1,
                'msg': '操作失败1',
            }
            return Response(response, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            if questionnaire.id > 0:
                response = {
                    'code': 0,
                    'msg': '操作成功',
                    'id': questionnaire.id
                }
                return Response(response, status=status.HTTP_200_OK)
            else:
                response = {
                    'code': -1,
                    'msg': '操作失败',
                }
                return Response(response, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    else:
        response = {
            'code': -1,
            'msg': '缺少参数',
        }
    return Response(response, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST', ])
@transaction.atomic
def addQuestion(request):  # 创建一个问题
    title = request.data.get('title')
    type = request.data.get('type')
    wjId = request.data.get('questionnaire_id')
    must = request.data.get('must')
    question_id = request.data.get('question_id')
    options = request.data.get('options')
    remark = request.data.get('remark')
    score = request.data.get('score')
    is_positioning = request.data.get('is_positioning')

    if title and type and wjId:
        if type in ['fill', 'grade', 'multi', 'single']:
            if question_id:  # 问题已经存在

                question = Question.objects.get(id=question_id)
                question.type = type
                question.title = title
                question.must = must
                question.remark = remark
                if score is not None:
                    question.score = score
                if is_positioning is not None:
                    question.is_positioning = is_positioning
                question.save()

                if type == 'grade':
                    grade_type = request.data.get('grade_type')
                    degree_min = request.data.get('degree_min')
                    degree_max = request.data.get('degree_max')
                    range = request.data.get('range')
                    start = request.data.get('start')

                    if grade_type and degree_min and degree_max and range and start:
                        if GradeQuestionAttribute.objects.filter(questionId=question_id).count() == 0:
                            GradeQuestionAttribute.objects.create(questionId=question_id, grade_type=grade_type,
                                                                  degree_min=degree_min, degree_max=degree_max,
                                                                  range=range, start=start)
                            response = {
                                'question_id': question_id,
                                'code': 0
                            }
                            return Response(response, status=status.HTTP_201_CREATED)
                        else:
                            GradeQuestionAttribute.objects.filter(questionId=question_id).update(grade_type=grade_type,
                                                                                                 degree_min=degree_min,
                                                                                                 degree_max=degree_max,
                                                                                                 range=range,
                                                                                                 start=start)
                            response = {
                                'question_id': question_id,
                                'code': 0
                            }
                            return Response(response, status=status.HTTP_201_CREATED)
                    else:
                        response = {
                            'code': 0,
                            'msg': '参数错误'
                        }
                        return Response(response, status=status.HTTP_400_BAD_REQUEST)
                elif type == 'multi' or type == 'single':
                    ids = list()

                    for item in options:
                        ids.append(item['option_id'])
                    all_options = Options.objects.filter(questionId=question_id)
                    for item in all_options:
                        if item.id not in ids:
                            item.delete()

                    for item in options:
                        if item.get('option_id') == 0:
                            if item.get('is_correct') is not None:
                                option = Options.objects.create(title=item.get('title'), questionId=question_id,
                                                                limit=None, remain=None,
                                                                is_correct=item.get('is_correct'))
                                if item.get('is_correct') and type == 'single':
                                    question.correct_option = option.id
                                    question.save()
                            elif item.get('limit') == 0:
                                Options.objects.create(title=item.get('title'), questionId=question_id, limit=None,
                                                       remain=None)
                            else:
                                Options.objects.create(title=item.get('title'), questionId=question_id,
                                                       limit=item.get('limit'), remain=item.get('limit'))
                        else:
                            is_correct = item.get('is_correct')
                            limit = item.get('limit')
                            if limit == 0:
                                Options.objects.filter(id=item.get('option_id')).update(title=item.get('title'),
                                                                                        limit=None, remain=None,
                                                                                        is_correct=is_correct)
                            else:
                                Options.objects.filter(id=item.get('option_id')).update(title=item.get('title'),
                                                                                        limit=limit,
                                                                                        remain=limit,
                                                                                        is_correct=is_correct)
                            if is_correct is not None:
                                if is_correct and type == 'single':
                                    option = Options.objects.get(id=item.get('option_id'))
                                    question.correct_option = option.id
                                    question.save()

                    response = {
                        'code': 0,
                        'status': '创建成功',
                        'question_id': question_id
                    }
                    return Response(response, status=status.HTTP_200_OK)
                elif type == 'fill':
                    row = request.data.get('row')
                    question.correct_answer = request.data.get('correct_answer')
                    question.row = row
                    question.save()
                    Question.objects.get(id=question_id)
                    response = {
                        'code': 0,
                        'status': '创建成功',
                        'question_id': question_id
                    }
                    return Response(response, status=status.HTTP_200_OK)

            else:
                question = Question.objects.create(type=type, title=title, must=must, wjId=wjId, remark=remark)
                if score is not None:
                    question.score = score
                if is_positioning is not None:
                    question.is_positioning = is_positioning
                question.save()
                question_id = question.id
                if type == 'multi' or type == 'single':
                    if options is None:
                        response = {
                            'code': -1,
                            'status': '参数错误1'
                        }
                        return Response(response, status=status.HTTP_400_BAD_REQUEST)
                    for item in options:
                        is_correct = item.get('is_correct')
                        limit = item.get('limit')
                        if limit == 0:
                            option = Options.objects.create(questionId=question_id, title=item.get('title'),
                                                            limit=None, remain=None, is_correct=is_correct)
                        else:
                            option = Options.objects.create(questionId=question_id, title=item.get('title'),
                                                            limit=item.get('limit'),
                                                            remain=item.get('limit'), is_correct=is_correct)

                        if is_correct is not None:
                            if is_correct and type == 'single':
                                question.correct_option = option.id
                                question.save()

                    response = {
                        'question_id': question_id,
                        'code': 0,
                        'status': '创建成功'
                    }
                    return Response(response, status=status.HTTP_200_OK)
                if type == 'grade':
                    grade_type = request.data.get('grade_type')
                    degree_min = request.data.get('degree_min')
                    degree_max = request.data.get('degree_max')
                    range = request.data.get('range')
                    start = request.data.get('start')
                    if grade_type and degree_min and degree_max and range and start:
                        grade_question_attribute = GradeQuestionAttribute.objects.create(questionId=question_id,
                                                                                         grade_type=grade_type,
                                                                                         degree_min=degree_min,
                                                                                         degree_max=degree_max,
                                                                                         range=range,
                                                                                         start=start)
                        response = {
                            'question_id': question_id,
                            'code': 0,
                            'status': '创建成功'
                        }
                        return Response(response, status=status.HTTP_200_OK)
                    else:
                        response = {
                            'code': 0,
                            'msg': '参数错误'
                        }
                        return Response(response, status=status.HTTP_400_BAD_REQUEST)
                if type == 'fill':
                    row = request.data.get('row')
                    correct_answer = request.data.get('correct_answer')
                    question.correct_answer = correct_answer
                    question.row = row
                    question.save()
                    response = {
                        'code': 0,
                        'msg': '创建成功',
                        'id': question.id
                    }
                    return Response(response, status=status.HTTP_200_OK)
                else:
                    response = {
                        'code': -1,
                        'msg': '创建失败'
                    }
                    return Response(response, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({'code': -1, 'msg': '参数错误2'}, status=status.HTTP_400_BAD_REQUEST)

    else:
        response = {
            'code': -1,
            'msg': '缺少参数'
        }
        return Response(response, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST', ])
@transaction.atomic
def editQuestionnaire(request):
    questionnaire_id = request.data.get('questionnaire_id')
    title = request.data.get('title')
    desc = request.data.get('desc')
    questions = request.data.get('questions')
    limit = request.data.get('limit')
    if questionnaire_id is None or title is None or desc is None or questions is None:
        return Response({'code': -1, 'msg': '缺少问卷参数'}, status=status.HTTP_200_OK)
    if Questionnaire.objects.filter(id=questionnaire_id).count() == 0:
        return Response({'code': -1, 'msg': '问卷不存在'}, status=status.HTTP_200_OK)

    questionnaire = Questionnaire.objects.get(id=questionnaire_id)
    questionnaire.title = title
    questionnaire.desc = desc
    if limit == 0:
        questionnaire.limit = None
    else:
        questionnaire.limit = limit
    questionnaire.save()

    delete_questions = Question.objects.filter(wjId=questionnaire_id)
    for dq in delete_questions:
        Options.objects.filter(questionId=dq.id).delete()
        GradeQuestionAttribute.objects.filter(questionId=dq.id).delete()
        dq.delete()

    question_ids = list()
    for question in questions:
        title = question.get('title')
        type = question.get('type')
        must = question.get('must')
        remark = question.get('remark')
        if title is None or type is None or must is None:
            return Response({'code': -1, 'msg': '缺少问题参数'}, status=status.HTTP_200_OK)
        question_object = Question.objects.create(title=title, type=type, must=must, wjId=questionnaire_id,
                                                  remark=remark)
        question_ids.append(question_object.id)
        if type == 'single' or type == 'multi':
            options = question.get('options')
            if options is None:
                return Response({'code': -1, 'msg': '缺少选项参数'}, status=status.HTTP_200_OK)
            for option in options:
                title = option.get('title')
                limit = option.get('limit')
                if limit != 0:
                    Options.objects.create(title=title, questionId=question_object.id, limit=limit, remain=limit)
                else:
                    Options.objects.create(title=title, questionId=question_object.id, limit=None, remain=None)
        elif type == 'grade':
            detail = question.get('detail')
            if detail is None:
                return Response({'code': -1, 'msg': '缺少detail参数'}, status=status.HTTP_200_OK)
            grade_type = detail.get('grade_type')
            degree_min = detail.get('degree_min')
            degree_max = detail.get('degree_max')
            range = detail.get('range')
            start = detail.get('start')
            print('detail', detail)
            print('type', grade_type)
            GradeQuestionAttribute.objects.create(questionId=question_object.id, grade_type=grade_type,
                                                  degree_min=degree_min, degree_max=degree_max, range=range,
                                                  start=start)
        elif type == 'fill':
            row = question.get('row')
            is_positioning = question.get('is_positioning')
            if is_positioning is not None:
                question_object.is_positioning = is_positioning
            question_object.row = row
            question_object.save()
    return Response({'code': 0, 'msg': '成功'}, status=status.HTTP_200_OK)


#  这里还需要加一个删除grade type的关联的GradeQuestionAttribute删除 还没做 不必做了已经用不上了
@api_view(['POST', ])
def deleteQuestion(request):
    id = request.data.get('question_id')
    question = Question.objects.filter(id=id)
    if question.count() == 0:
        response = {
            'code': -1,
            'msg': '不存在该问题'
        }
        return Response(response, status=status.HTTP_404_NOT_FOUND)
    Question.objects.get(id=id).delete()
    response = {
        'code': 0,
        'msg': '删除成功'
    }
    return Response(response, status=status.HTTP_204_NO_CONTENT)


@api_view(['POST', ])
def deleteQuestionnaire(request):
    id = request.data.get('questionnaire_id')
    questionnaire = Questionnaire.objects.filter(id=id)
    if questionnaire.count() == 0:
        response = {
            'code': -1,
            'msg': '不存在'
        }
        return Response(response, status=status.HTTP_404_NOT_FOUND)
    Questionnaire.objects.get(id=id).delete()
    response = {
        'code': 0,
        'msg': '删除成功'
    }
    return Response(response, status=status.HTTP_204_NO_CONTENT)


@api_view(['POST', ])
def getSettings(request):
    wid = request.data.get('questionnaire_id')
    if wid:
        wj = Questionnaire.objects.filter(id=wid).first()
        if wj.start_time and wj.end_time:
            s = wj.start_time.__str__().split()
            t = wj.end_time.__str__().split()
            # s = (wj.start_time + datetime.timedelta(hours=8)).__str__().split()
            # t = (wj.end_time + datetime.timedelta(hours=8)).__str__().split()
            # start_time = s[0] + 'T' + s[1][:-6] + '+08:00'
            # end_time = t[0] + 'T' + t[1][:-6] + '+08:00'
            start_time = s[0] + 'T' + s[1]
            end_time = t[0] + 'T' + t[1][:-6] + 'Z'
        else:
            if wj.publish_time:
                p = wj.publish_time.__str__().split()
                start_time = p[0] + 'T' + p[1]
                end_time = "3000-12-31T15:59:59.000Z"
            else:
                start_time = ''
                end_time = ''
        response = {
            'code': 0,
            'msg': 'success',
            'start': [
                start_time,
                end_time],
            'show_number': wj.show_number,
            'is_out_of_order': wj.is_out_of_order,
            'is_allowed_to_change': wj.is_allowed_to_change,
            'is_remind': wj.is_remind,
            'is_set_date': wj.is_set_date
        }
        return Response(response, status.HTTP_200_OK)
    else:
        return Response({'code': -1, 'msg': '参数错误:缺少参数'}, status.HTTP_200_OK)


@api_view(['POST', ])
def changeSettings(request):
    wid = request.data.get('questionnaire_id')
    if wid:
        wj = Questionnaire.objects.filter(id=wid).first()

        start = request.data.get('start')
        show_number = request.data.get('show_number')
        is_out_of_order = request.data.get('is_out_of_order')
        is_allowed_to_change = request.data.get('is_allowed_to_change')
        is_remind = request.data.get('is_remind')
        is_set_date = request.data.get('is_set_date')

        if start:
            s = start[0]
            e = start[1]

            if s[-1] != 'Z':
                wj.start_time = datetime.datetime.strptime(s[:-6], "%Y-%m-%dT%H:%M:%S.%f")
                wj.end_time = datetime.datetime.strptime(e[:-6], "%Y-%m-%dT%H:%M:%S.%f")
            else:
                wj.start_time = datetime.datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%fZ")  # + datetime.timedelta(hours=8)
                wj.end_time = datetime.datetime.strptime(e, "%Y-%m-%dT%H:%M:%S.%fZ")  # + datetime.timedelta(hours=8)
            wj.save()
            print(start)
        if show_number is not None:
            wj.show_number = show_number
            wj.save()
            print('show: ' + str(show_number))
        if is_out_of_order is not None:
            wj.is_out_of_order = is_out_of_order
            wj.save()
            print('order: ' + str(wj.is_out_of_order))
        if is_allowed_to_change is not None:
            wj.is_allowed_to_change = is_allowed_to_change
            wj.save()
            print('allow: ' + str(is_allowed_to_change))
        if is_remind is not None:
            wj.is_remind = is_remind
            wj.save()
            print('remind: ' + str(is_remind))
        if is_set_date is not None:
            wj.is_set_date = is_set_date
            if not is_set_date:
                wj.start_time = None
                wj.end_time = None
            wj.save()
            print('set date: ' + str(is_set_date))

        return Response({'code': 0, 'msg': 'success'}, status.HTTP_200_OK)
    else:
        return Response({'code': -1, 'msg': '参数错误:缺少参数questionnaire_id'}, status.HTTP_200_OK)


@api_view(['POST', ])
def editExamQuestionnaire(request):
    questionnaire_id = request.data.get('questionnaire_id')
    title = request.data.get('title')
    desc = request.data.get('desc')
    questions = request.data.get('questions')
    if questionnaire_id is None or title is None or desc is None or questions is None:
        return Response({'code': -1, 'msg': '缺少问卷参数'}, status=status.HTTP_200_OK)
    if Questionnaire.objects.filter(id=questionnaire_id).count() == 0:
        return Response({'code': -1, 'msg': '问卷不存在'}, status=status.HTTP_200_OK)

    questionnaire = Questionnaire.objects.get(id=questionnaire_id)
    questionnaire.title = title
    questionnaire.desc = desc
    questionnaire.save()

    delete_questions = Question.objects.filter(wjId=questionnaire_id)
    for dq in delete_questions:
        Options.objects.filter(questionId=dq.id).delete()
        GradeQuestionAttribute.objects.filter(questionId=dq.id).delete()
        dq.delete()

    # question_ids = list()
    for question in questions:
        title = question.get('title')
        type = question.get('type')
        must = question.get('must')
        remark = question.get('remark')
        score = question.get('score')
        if title is None or type is None or must is None:
            return Response({'code': -1, 'msg': '缺少问题参数'}, status=status.HTTP_200_OK)
        question_object = Question.objects.create(title=title, type=type, must=must, wjId=questionnaire_id,
                                                  remark=remark, score=score)
        # question_ids.append(question_object.id)
        if type == 'single' or type == 'multi':
            options = question.get('options')
            if options is None:
                return Response({'code': -1, 'msg': '缺少选项参数'}, status=status.HTTP_200_OK)
            for option in options:
                title = option.get('title')
                is_correct = option.get('is_correct')
                option_object = Options.objects.create(title=title, questionId=question_object.id,
                                                       is_correct=is_correct)
                if is_correct and type == 'single':
                    question_object.correct_option = option_object.id
                    question_object.save()
        elif type == 'fill':
            row = question.get('row')
            question_object.row = row
            correct_answer = question.get('correct_answer')
            if correct_answer is not None:
                question_object.correct_answer = correct_answer
            question_object.save()

    return Response({'code': 0, 'msg': '创建成功'}, status=status.HTTP_200_OK)
